﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Musik.Data;
using Musik.Model;
using System.Data.Entity.Infrastructure;
using System.Data;
using System.Globalization;

namespace MusikWebApi.Controllers
{
    public class AlbumController : ApiController
    {
        private MusikContext db = new MusikContext();

        // GET api/albums
        public IEnumerable<Album> GetAlbums()
        {
            return db.Albums.Include("Artists").Include("Songs").AsEnumerable();
        }

        // GET api/album/5
        public Album GetAlbum(int id)
        {
            Album album = db.Albums.Find(id);
            if (album == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return album;
        }

        // GET api/album/song1
        public Album GetAlbum(string title)
        {
            Album album = db.Albums.Where(x => x.Title == title).FirstOrDefault();
            if (album == null)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
            }
            return album;
        }

        // POST api/albums
        public HttpResponseMessage PostAlbum([FromBody]Album album)
        {
            // header
            //Content-type: application/json

            // req body
            //{
            //"Title": "I Love WebServices",
            //"ReleaseDate": "2002.11.03",
            //"Producer": "The Big Chicken"
            //}

            if (ModelState.IsValid)
            {
                //CheckArtistsInAlbums(album);
                db.Albums.Add(album);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, album);
                //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = album.AlbumId }));
                response.Headers.Location = new Uri(this.Request.RequestUri + album.AlbumId.ToString(CultureInfo.InvariantCulture));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }

        // PUT api/albums/5
        public HttpResponseMessage PutAlbum(int id, [FromBody]Album album)
        {
            // header
            //Content-type: application/json


            // req body
            //{
            //"AlbumId": "1",
            //"Title": "I Love WebServicessss",
            //"ReleaseDate": "2002.11.03",
            //"Producer": "The Big Chicken"
            //}

            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != album.AlbumId)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            //CheckArtistsInAlbums(album);
            db.Entry(album).State = EntityState.Modified;
            
            //var oldAlbum = db.Albums.SingleOrDefault(u => u.AlbumId == album.AlbumId);
            //oldAlbum = album;
            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.Forbidden, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }

        // DELETE api/albums/5
        public HttpResponseMessage DeleteAlbum(int id)
        {
            Album album = db.Albums.Find(id);
            if (album == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.Albums.Remove(album);

            try
            {
                db.SaveChanges();
            }
            catch(DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.Forbidden, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, album);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        // important method to create new list of artist and add it to album
        // but the problem is existing yet
        private void CheckArtistsInAlbums(Album album)
        {
            var artists = new List<Artist>();
            foreach(var artist in album.Artists)
            {
                var a = db.Artists.FirstOrDefault(x => x.ArtistId == artist.ArtistId);
                if (a == null)
                {
                    a = new Artist();
                }
                artists.Add(a);
            }
            album.Artists = artists;
        }
    }
}